package client

import (
	"context"
	"github.com/ecodeclub/ekit/syncx/atomicx"
	"google.golang.org/grpc"
	intrv1 "jk-time/webook/api/proto/gen/intr/v1"
	"math/rand"
)

type InteractiveSerivceClient struct {
	remote    intrv1.InteractiveSerivceClient
	local     intrv1.InteractiveSerivceClient
	threshold *atomicx.Value[int32]
}

func NewInteractiveClient(remote intrv1.InteractiveSerivceClient, local intrv1.InteractiveSerivceClient,
	threshold int32) InteractiveSerivceClient {
	return InteractiveSerivceClient{
		remote:    remote,
		threshold: atomicx.NewValueOf(threshold),
		local:     local,
	}
}
func (i *InteractiveSerivceClient) UpdateThreshold(threshold int32) {
	i.threshold.Store(threshold)
}
func (i *InteractiveSerivceClient) selectClient() intrv1.InteractiveSerivceClient {
	n := rand.Int31n(100)
	if n < i.threshold.Load() {
		return i.remote
	}
	return i.local
}
func (i *InteractiveSerivceClient) IncrReadCnt(ctx context.Context, in *intrv1.IncrReadCntRequest, opts ...grpc.CallOption) (*intrv1.IncrReadCntResponse, error) {
	return i.selectClient().IncrReadCnt(ctx, in, opts...)
}

func (i *InteractiveSerivceClient) Like(ctx context.Context, in *intrv1.LikeRequest, opts ...grpc.CallOption) (*intrv1.LikeResponse, error) {
	return i.selectClient().Like(ctx, in, opts...)
}

func (i *InteractiveSerivceClient) CancelLike(ctx context.Context, in *intrv1.CancelLikeRequest, opts ...grpc.CallOption) (*intrv1.CancelLikeResponse, error) {
	return i.selectClient().CancelLike(ctx, in, opts...)
}

func (i *InteractiveSerivceClient) Collect(ctx context.Context, in *intrv1.CollectRequest, opts ...grpc.CallOption) (*intrv1.CollectResponse, error) {
	return i.selectClient().Collect(ctx, in, opts...)
}

func (i *InteractiveSerivceClient) Get(ctx context.Context, in *intrv1.GetRequest, opts ...grpc.CallOption) (*intrv1.GetResponse, error) {
	return i.selectClient().Get(ctx, in, opts...)
}

func (i *InteractiveSerivceClient) GetByIds(ctx context.Context, in *intrv1.GetByIdsRequest, opts ...grpc.CallOption) (*intrv1.GetByIdsResponse, error) {
	return i.selectClient().GetByIds(ctx, in, opts...)
}
